const jwt = require('jsonwebtoken')

const { getUserInfo, createUser, updateByIds } = require('../service/user.service');
const { rejectRegisterError, userLoginError, updatePasswordError } = require('../constant/err.type');
const { errorRequest } = require('../utils/util');
const { JWT_SECRET } = require('../config/config.default')

class UserController {
  async register(ctx, next) {
    try {
      // 1.获取数据
      const { user_name, password, is_admin } = ctx.request.body;
      // 2.操作数据库
      const res = await createUser(user_name, password, is_admin);
      // 3.返回结果
      ctx.body = {
        code: 0,
        message: '用户注册成功',
        result: {
          id: res.id,
          user_name: res.user_name
        }
      };
    } catch (error) {
      errorRequest(ctx, rejectRegisterError, error);
    }
  }

  async login(ctx, next) {
    const { user_name } = ctx.request.body
    try {
      const { password, ...res } = await getUserInfo({ user_name });
      ctx.body = {
        code: 0,
        message: '用户登录成功',
        result: {
          // jwt.sign 使用指定的密钥对payload进行签名，并生成一个JWT
          token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' }),
        }
      }
      await next()
    } catch (error) {
      errorRequest(ctx, userLoginError, error)
    }
  }


  async changePassword(ctx, next) {
    const password = ctx.request.body.password;
    const id = ctx.state.user.id;
    const flag = await updateByIds({ id, password });
    if (flag) {
      ctx.body = {
        code: 0,
        message: '修改密码成功',
        result: ''
      }
    } else {
      errorRequest(ctx, updatePasswordError, '修改密码失败')
    }

    await next();
  }
}

module.exports = new UserController();